package com.orange.fastdfsjava.utils;

import com.orange.fastdfsjava.pojo.FastDfsFile;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;

@Slf4j
public class FastDFSClient {

    static {
        //加载fastDFS客户端的配置文件
        try {
            ClientGlobal.initByProperties("config/fastdfs-client.properties");
            log.info("network_timeout = {} ms", ClientGlobal.g_network_timeout);
            log.info("charset= {}", ClientGlobal.g_charset);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param file
     * @param fastDFSFile
     * @return
     * @throws IOException
     */
    public static FastDfsFile upload(MultipartFile file, FastDfsFile fastDFSFile) throws IOException {
        byte[] file_buff = null;
        //把文件转成输入流
        InputStream inputStream = file.getInputStream();
        if (inputStream != null) {
            //获取输入流中可读取的数据大小
            int len = inputStream.available();
            //创建足够大的缓冲区
            file_buff = new byte[len];
            //一次性把输入流中的数据全都读入到缓冲区file_buff,那file_buff就要足够大,占用内存也会很大
            inputStream.read(file_buff);
        }
        //关闭输入流
        inputStream.close();

        //通过fastDSF的client代码访问tracker和storage
        try {
            //创建tracker的客户端
            TrackerClient trackerClient = new TrackerClient(ClientGlobal.getG_tracker_group());
            //通过TrackerClient对象获取TrackerServer信息
            TrackerServer trackerServer = trackerClient.getTrackerServer();
            StorageServer storageServer = null;

            //定义storage的客户端,建立与Storage服务器的连接
            StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);

            //文件元信息
            NameValuePair[] metaList = new NameValuePair[1];
            metaList[0] = new NameValuePair("fileName", fastDFSFile.getFileName());

            //执行上传
            String fileId = storageClient.upload_file1(file_buff, fastDFSFile.getExt(), metaList);
            log.info("upload success. file id is: {}", fileId);
            fastDFSFile.setFileId(fileId);
            fastDFSFile.setFilePath(fileId);
            fastDFSFile.setFileSize(file.getSize());
            fastDFSFile.setCreateTime(LocalDateTime.now());
            fastDFSFile.setUpdateTime(LocalDateTime.now());
            //通过调用service及dao将文件的路径存储到数据库中

            //关闭storage客户端
            storageClient.close();
            return fastDFSFile;
        } catch (Exception e) {
            log.error("上传文件失败：", e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除文件
     *
     * @param file_id
     * @return
     * @throws IOException
     * @throws MyException
     */
    public static Boolean delete(String file_id) throws IOException, MyException {
        //通过fastDSF的client代码访问tracker和storage
        //创建tracker的客户端
        TrackerClient trackerClient = new TrackerClient(ClientGlobal.getG_tracker_group());
        //通过TrackerClient对象获取TrackerServer信息
        TrackerServer trackerServer = trackerClient.getTrackerServer();
        StorageServer storageServer = null;

        //定义storage的客户端,建立与Storage服务器的连接
        StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);

        //查询文件
        //upload success. file id is: group1/M00/00/00/wKjljWXHAauARHa2AAWwwNOt0hY257.png
        String[] splitStr = file_id.split("/");
        String group_name = splitStr[0];//group1
        String remoteFileName = "";//M00/00/00/wKjljWXHAauARHa2AAWwwNOt0hY257.png
        for (int i = 1; i < splitStr.length; i++) {
            remoteFileName += splitStr[i];
            if (i != splitStr.length - 1) {
                remoteFileName += "/";
            }
        }
        log.info("group_name : {}", group_name);
        log.info("remoteFileName : {}", remoteFileName);
        FileInfo fileInfo = storageClient.query_file_info(group_name, remoteFileName);
        log.info("fileInfo = {}", fileInfo);

        if (fileInfo == null) {
            log.info("您删除的文件信息不存在，请核对后再次删除......");
            return false;
        }

        storageClient.delete_file1(file_id);
        log.info("删除成功");

        //关闭storage客户端
        storageClient.close();
        return true;
    }

    /**
     * 下载文件
     *
     * @param file_id
     * @throws IOException
     * @throws MyException
     */
    public static byte[] downloadFastFile(String file_id) throws IOException, MyException {
        //通过fastDSF的client代码访问tracker和storage
        //创建tracker的客户端
        TrackerClient trackerClient = new TrackerClient(ClientGlobal.getG_tracker_group());
        //通过TrackerClient对象获取TrackerServer信息
        TrackerServer trackerServer = trackerClient.getTrackerServer();
        StorageServer storageServer = null;

        //定义storage的客户端,建立与Storage服务器的连接
        StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);

        //查询文件
        //upload success. file id is: group1/M00/00/00/wKjljWXHAauARHa2AAWwwNOt0hY257.png
        String[] splitStr = file_id.split("/");
        String group_name = splitStr[0];//group1
        String remoteFileName = "";//M00/00/00/wKjljWXHAauARHa2AAWwwNOt0hY257.png
        for (int i = 1; i < splitStr.length; i++) {
            remoteFileName += splitStr[i];
            if (i != splitStr.length - 1) {
                remoteFileName += "/";
            }
        }
        log.info("group_name : {}", group_name);
        log.info("remoteFileName : {}", remoteFileName);
        FileInfo fileInfo = storageClient.query_file_info(group_name, remoteFileName);
        log.info("fileInfo = {}", fileInfo);

        if (fileInfo == null) {
            log.info("您下载的文件信息不存在，请核对后再次下载......");
            return null;
        }

        //下载操作,传文件id返回字节流
        byte[] bytes = storageClient.download_file1(file_id);

        //关闭storage客户端
        storageClient.close();
        return bytes;
    }
}
